package com.neustudy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neustudy.base.exception.NeuStudyExecption;
import com.neustudy.base.model.PageParams;
import com.neustudy.base.model.PageResult;
import com.neustudy.content.mapper.*;
import com.neustudy.content.model.dto.AddCourseDto;
import com.neustudy.content.model.dto.CourseBaseInfoDto;
import com.neustudy.content.model.dto.EditCourseDto;
import com.neustudy.content.model.dto.QueryCourseParamsDto;
import com.neustudy.content.model.po.*;
import com.neustudy.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author WKX
 * @version 1.0
 * @describe todo
 * @create: 2024-11-05 12:41
 */
@Slf4j
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams params, QueryCourseParamsDto queryCourseParamsDto) {
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());

        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());
        Page<CourseBase> list = courseBaseMapper.selectPage(page,lambdaQueryWrapper);
        PageResult<CourseBase> pageResult = new PageResult<>(list.getRecords(), list.getTotal(),params.getPageNo(), params.getPageSize());
        return pageResult;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {

        //合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            throw new NeuStudyExecption("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new NeuStudyExecption("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new NeuStudyExecption("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new NeuStudyExecption("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new NeuStudyExecption("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new NeuStudyExecption("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new NeuStudyExecption("收费规则为空");
        }
        //新增对象
        CourseBase courseBaseNew = new CourseBase();
        //将填写的课程信息赋值给新增对象
        BeanUtils.copyProperties(dto,courseBaseNew);
        //设置审核状态
        courseBaseNew.setAuditStatus("202002");
        //设置发布状态
        courseBaseNew.setStatus("203001");
        //机构id
        courseBaseNew.setCompanyId(companyId);
        //添加时间
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBaseNew);
        if(insert<=0){
            throw new NeuStudyExecption("新增课程基本信息失败");
        }
        //向课程营销表保存课程营销信息
        //课程营销信息
        CourseMarket courseMarketNew = new CourseMarket();
        Long courseId = courseBaseNew.getId();
        BeanUtils.copyProperties(dto,courseMarketNew);
        courseMarketNew.setId(courseId);
        int i = saveCourseMarket(courseMarketNew);
        if(i<=0){
            throw new NeuStudyExecption("保存课程营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseId);

    }
    //保存课程营销信息
    private int saveCourseMarket(CourseMarket courseMarketNew){
        //收费规则
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new NeuStudyExecption("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue()<=0){
                throw new NeuStudyExecption("课程为收费价格不能为空且必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarketNew.getId());
        if(courseMarketObj == null){
            return courseMarketMapper.insert(courseMarketNew);
        }else{
            BeanUtils.copyProperties(courseMarketNew,courseMarketObj);
            courseMarketObj.setId(courseMarketNew.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }
    //根据课程id查询课程基本信息，包括基本信息和营销信息
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId,EditCourseDto editCourseDto){
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());
        if(courseBase==null){
            NeuStudyExecption.cast("课程不存在");
        }
        if(!courseBase.getCompanyId().equals(companyId)){
            NeuStudyExecption.cast("本机构只能修改本机构的课程");
        }
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int i = courseBaseMapper.updateById(courseBase);
        if(i<0){
            NeuStudyExecption.cast("修改课程失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        int j = courseMarketMapper.updateById(courseMarket);
        if(j<0){
            NeuStudyExecption.cast("修改课程失败");
        }
        return getCourseBaseInfo(editCourseDto.getId());
    }

    @Override
    public void deleteCourseBase(Long companyId, Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase==null){
            NeuStudyExecption.cast("课程不存在");
        }
        if(!courseBase.getCompanyId().equals(companyId)){
            NeuStudyExecption.cast("本机构只能删除本机构的课程");
        }
        if(!courseBase.getAuditStatus().equals("202002")){
            NeuStudyExecption.cast("只能删除未提交审核的课程");
        }else {
            LambdaQueryWrapper<CourseTeacher> courseteacherwrapper = new LambdaQueryWrapper<>();
            courseteacherwrapper.eq(CourseTeacher::getCourseId,courseId);
            int i = courseTeacherMapper.delete(courseteacherwrapper);
            if(i < 0){
                NeuStudyExecption.cast("删除课程教师失败");
            }

            LambdaQueryWrapper<TeachplanMedia> teachplanmediawrapper = new LambdaQueryWrapper<>();
            teachplanmediawrapper.eq(TeachplanMedia::getCourseId,courseId);
            i = teachplanMediaMapper.delete(teachplanmediawrapper);
            if(i < 0){
                NeuStudyExecption.cast("删除课程资源失败");
            }

            LambdaQueryWrapper<Teachplan> teachplanwrapper = new LambdaQueryWrapper<>();
            teachplanwrapper.eq(Teachplan::getCourseId,courseId);
            i = teachplanMapper.delete(teachplanwrapper);
            if(i < 0){
                NeuStudyExecption.cast("删除课程计划失败");
            }

            i = courseMarketMapper.deleteById(courseId);
            if(i < 0){
                NeuStudyExecption.cast("删除课程营销信息失败");
            }

            i = courseBaseMapper.deleteById(courseId);
            if(i < 0){
                NeuStudyExecption.cast("删除课程信息失败");
            }
        }
    }


}
